# Copyright (c) 2024, json_wang and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
import pandas as pd
from frappe.utils.file_manager import get_file_path


class CP_Invoice_Import(Document):
	@frappe.whitelist()
	def do_import(self):
		# print(self.meta.name)		
		# print(self.invoice_list_file)
		file_path = get_file_path(self.invoice_list_file)
		# print(file_path)		
		df = pd.read_excel(file_path,sheet_name='信息汇总表',dtype={"发票代码":str,"发票号码":str,"数电票号码":str},header=0)
		df['发票代码'] = df['发票代码'].fillna("")
		df['发票号码'] = df['发票号码'].fillna("")
		df['数电票号码'] = df['数电票号码'].fillna("")	
		new_df = df.fillna("")	
		print(new_df.dtypes)
		new_df['invoice_no'] = df.apply(
    		lambda row: row['发票代码'] + '#' + row['发票号码'] if len(row['发票代码']) > 3 else row['数电票号码'], axis=1)
		self.child_invoice = []
		for index, row in new_df.iterrows():
			self.append("child_invoice", row.to_dict())			
		self.save()
		df_sum = new_df.groupby(["invoice_no", "发票代码", "发票号码", "数电票号码", "销方名称","开票日期"])["价税合计"].sum().reset_index()			
		# 使用iterrows遍历DataFrame中的每一行
		for index, row in df_sum.iterrows():				
			print(f"index:{index},invoice_name:{row.invoice_no}")		
			if not frappe.db.exists("CP_Invoice", row.invoice_no, cache=True):
				print(f'发票号{row.invoice_no}不存在，执行新增操作。row:{row}')
				doc = frappe.new_doc('CP_Invoice')
				doc.invoice_no = row.invoice_no
				doc.发票代码=str(row['发票代码'])
				doc.发票号码=str(row['发票号码'])
				doc.数电票号码=str(row['数电票号码'])				
				doc.销方名称=str(row['销方名称'])				
				doc.开票日期=str(row['开票日期'])				
				doc.价税合计=str(row['价税合计'])				
				doc.insert(ignore_permissions=True)
		

